﻿using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebDiagnostics
{
    public class WebDiagnosticsHandler : IHttpHandler
    {
        public const string DiagnosersToExecuteKey = "Diagnoser";

        private readonly DiagnoserFactory _diagnoserFactory;

        public WebDiagnosticsHandler()
            : this(DiagnoserFactory.Current)
        {
        }
        public WebDiagnosticsHandler(DiagnoserFactory diagnoserFactory)
        {
            _diagnoserFactory = diagnoserFactory;
        }

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            ProcessRequest(new HttpContextWrapper(context));
        }

        public void ProcessRequest(HttpContextBase context)
        {
            string diagnoserNamesToExecuteQuery = context.Request[DiagnosersToExecuteKey] ?? string.Empty;

            IEnumerable<Diagnosis> diagnoses = GetDiagnoses(diagnoserNamesToExecuteQuery, context);

            bool isAjaxRequest = diagnoses.Any();

            IDiagnosticsResponseRenderer renderer;

            context.Response.Clear();
            context.Response.ClearContent();

            if (isAjaxRequest)
                renderer = new AjaxResponseRenderer(context, diagnoses);
            else
                renderer = new PageResponseRenderer(context, _diagnoserFactory.GetDiagnosers());

            renderer.Render(context.Response.Output);
        }

        protected IEnumerable<Diagnosis> GetDiagnoses(string diagnoserKeysQuery, HttpContextBase context)
        {
            IEnumerable<string> diagnoserKeys = diagnoserKeysQuery.Split(new[] { ',', ';' });

            IEnumerable<IDiagnoser> diagnosersToExecute = _diagnoserFactory.GetDiagnosersByKey(diagnoserKeys);

            foreach (var diagnoser in diagnosersToExecute)
                yield return diagnoser.Diagnose(context);
        }
    }
}
